package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.payment.pbqzpay.PubuPayUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 定时任务调度测试
 *
 * @author admin
 */
@Component("lakalaOrderCheckTask")
public class LakalaOrderCheckTask {
    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITSmjOrderInfoService itSmjOrderInfoService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkOrder() throws Exception {
//        logger.info("CXZF订单查询..");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
        query.setChannel("lakala_pay");
        query.setStatus(1);
        String newdateTime = DateUtils.dealDate("5分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        query.getParams().put("beginCreateTime", newdateTime);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
        for (TOrderInfo orderInfo : orderInfos) {
            synchronized (this) {
                if (orderInfo.getValidTime().before(new Date()) || StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                    continue;
                }

                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String token = accountObj.getString("ck");
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("Authorization",token);
                headerMap.put("X-Client-PV","lKL_APP");
                headerMap.put("Host","wallet.lakala.com");
                headerMap.put("User-Agent","lakala_app/56 CFNetwork/3826.400.120 Darwin/24.3.0");


                JSONObject reqOrderObj = new JSONObject();
                reqOrderObj.put("outOrgCode", "37001010012");
                reqOrderObj.put("outSysCode", "MOBILE_PLATFORM");
                reqOrderObj.put("reqTime", sdf.format(new Date()));
                reqOrderObj.put("version", "3.0");
                reqOrderObj.put("signType",null);
                reqOrderObj.put("sign",null);
                JSONObject reqDataObj = new JSONObject();
                reqDataObj.put("merchantNo",accountObj.getString("lklShopno"));
                reqDataObj.put("termNo",accountObj.getString("lklTermno"));
                reqDataObj.put("outTradeNo",orderInfo.getId());
                reqDataObj.put("tradeNo",null);
                reqDataObj.put("outOrderNo",null);
                reqDataObj.put("outOrderSource",null);
                reqOrderObj.put("reqData",reqDataObj);
                logger.info("查单参数：{}", JSON.toJSONString(reqOrderObj));
                String submitPayUrl = "https://wallet.lakala.com/m/a/transv3/query";
                String submitPayRes = HttpUtils.sendJsonMessage(submitPayUrl,headerMap,reqOrderObj.toJSONString());
                logger.info("查单返回：{}", submitPayRes);
                JSONObject  submitPayResObj = JSONObject.parseObject(submitPayRes);
                if(submitPayResObj.getString("code").equals("BBS00000")){
                    JSONObject respDataObj = submitPayResObj.getJSONObject("respData");
                    if("SUCCESS".equals(respDataObj.getString("tradeState"))){
                        MsgPayResult msgPayResult = new MsgPayResult();
                        msgPayResult.setChannel(orderInfo.getChannel());
                        msgPayResult.setTradeNo(orderInfo.getId().toString());
                        msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                        msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                        msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                        msgPayResult.setChannelPayMsgResult(respDataObj.toJSONString());
                        ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                        chargeService.notifyUserPaySucc(orderInfo.getId());
                        logger.info("拉卡拉订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                    }

                }
            }
        }
    }


    private TRecipientInfo reLogin(TRecipientInfo tRecipientInfo) {
        long time = System.currentTimeMillis()/1000;
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        JSONObject  loginObj  = new JSONObject();
        loginObj.put("pwd",accountObj.getString("password"));
        loginObj.put("userName",tRecipientInfo.getChannelAccount());
        String sign = PubuPayUtils.getSign(time,loginObj,"");
        String loginUrl = "http://api.openpubu.com/open/login?token=&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
        String loginRes = HttpUtils.sendJsonMessage(loginUrl,headerMap,loginObj.toJSONString());
        JSONObject  loginResObj = JSONObject.parseObject(loginRes);
        if(loginResObj.getIntValue("status")!=200){
            return tRecipientInfo;
        }
        JSONObject userObj = (JSONObject)loginResObj.getJSONObject("body").getJSONArray("userList").get(0);

        String token = userObj.getString("token");
        accountObj.put("token",token);
        tRecipientInfo.setAccountJson(accountObj.toJSONString());
        tRecipientInfo.setOnline(1);
        userRecipientService.updateTRecipientInfo(tRecipientInfo);
        return tRecipientInfo;
    }

    private JSONObject rePaydetail(TRecipientInfo tRecipientInfo,JSONObject  reqOrderObj) {
        long time = System.currentTimeMillis()/1000;
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        String token = accountObj.getString("token");
        String sign = PubuPayUtils.getSign(time,reqOrderObj,token);
        String submitPayUrl = "http://api.openpubu.com/order/orderListNew?token="+token+"&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
        String submitPayRes = HttpUtils.sendJsonMessage(submitPayUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  submitPayResObj = JSONObject.parseObject(submitPayRes);
        return submitPayResObj;
    }

}
